package com.carefree.bookmall.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.carefree.bookmall.common.utils.Constant;
import com.carefree.bookmall.service.ShortMessageService;
import com.zhenzi.sms.ZhenziSmsClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName:ShortMessageServiceImpl
 * @Description:
 * @Author Tengbin
 */
@Service("shortMessageService")
public class ShortMessageServiceImpl implements ShortMessageService {

    @Resource
    private RedisTemplate<String, String> redisTemplate;


    /**
     * 发送短信验证码
     *
     * @param codeName     在redis中存储的名称
     * @param phone        手机号
     * @param numberLength 验证码位数
     * @return
     */
    @Override
    public boolean sendMessageByMobileNumber(String phone, int numberLength) {

        String result = "";

        // 初始化ZhenziSmsClient 榛子云短信
        String apiUrl = " ";
        String appId = " ";
        String appSecret = " ";
        ZhenziSmsClient zhenziSmsClient = new ZhenziSmsClient(apiUrl, appId, appSecret);

        // hutool 随机生成指定位数验证码
        String number = RandomUtil.randomNumbers(numberLength);

        // 短信发送参数
        Map<String, Object> params = new HashMap<>();
        params.put("number", phone);
        params.put("templateId", " ");
        String[] templateParams = new String[2];
        templateParams[0] = number;
        templateParams[1] = "5分钟";
        params.put("templateParams", templateParams);

        try {
            result = zhenziSmsClient.send(params);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 将返回的json字符串转为json对象
        JSONObject jsonObject = JSONUtil.parseObj(result);
        Integer code = (Integer) jsonObject.get("code");

        if (code == 0) {
            // 将生成的验证码存入到redis中,并设置过期时间为 5*60 s
            redisTemplate.opsForValue().set(Constant.REDIS_SMS_PREFIX + phone, number, 300);
            return true;
        }
        return false;
    }

    /**
     * 比较输入的验证码和redis存储的验证码是否一致
     *
     * @param phone     手机号
     * @param inputCoed 输入的验证码
     * @return
     */
    @Override
    public boolean compareSmsCode(String phone, String inputCode) {
        if (StringUtils.isAnyBlank(phone, inputCode)) {
            return false;
        }
        // 获取redis存储的验证码
        String storageCode = redisTemplate.opsForValue().get(Constant.REDIS_SMS_PREFIX + phone);
        return StringUtils.isNotBlank(storageCode) && storageCode.equals(inputCode);
    }
}
